package com.region.common.adapter.json.fastjson2;

import com.alibaba.fastjson2.JSON;
import com.region.common.adapter.json.JSONAdapter;
import com.region.common.adapter.json.JSONAdapterFactory;
import com.region.common.adapter.json.convert.JsonConvertor;

import java.lang.reflect.Type;

/**
 * @author 26225
 * @date 2024/9/8 11:14
 * @description
 */
public class Fastjson2Adapter<T> implements JSONAdapter<T> {

    public Fastjson2Adapter() throws ClassNotFoundException {
        Class.forName("com.alibaba.fastjson2.JSON");
    }

    @Override
    public T getTarget() {
        // no target
        return null;
    }

    @Override
    public String toJSONString(Object object) {
        for (JsonConvertor convertor : JSONAdapterFactory.getConvertors()) {
            if (convertor.isSerialized(object)) {
                return convertor.convertToString(object);
            }
        }
        return JSON.toJSONString(object);
    }

    @Override
    public Object toObject(String json) {
        return com.alibaba.fastjson.JSON.parse(json);
    }

    @Override
    public <K> K toObject(String json, Class<K> clazz) {
        for (JsonConvertor convertor : JSONAdapterFactory.getConvertors()) {
            if (convertor.isDeserialized(json, clazz)) {
                return convertor.convertToObject(json, clazz);
            }
        }
        return com.alibaba.fastjson.JSON.parseObject(json, clazz);
    }

    @Override
    public Object toObject(String json, Type type) {
        if (type instanceof Class) {
            return toObject(json, (Class) type);
        } else {
            for (JsonConvertor convertor : JSONAdapterFactory.getConvertors()) {
                if (convertor.isDeserialized(json, type)) {
                    return convertor.convertToObject(json, type);
                }
            }
            return JSON.parseObject(json, type);
        }
    }

}
